package com.gudaomai.ekproject.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.gudaomai.ekproject.common.CommonConstant;
import com.gudaomai.ekproject.common.CommonException;
import com.gudaomai.ekproject.common.Constant;
import com.gudaomai.ekproject.common.MsgConstant;
import com.gudaomai.ekproject.entity.Role;
import com.gudaomai.ekproject.entity.UserRole;
import com.gudaomai.ekproject.mapper.RoleMapper;
import com.gudaomai.ekproject.service.IRoleService;
import com.gudaomai.ekproject.service.ISysuserService;
import com.gudaomai.ekproject.service.IUserRoleService;
import com.gudaomai.ekproject.service.impl.BaseServiceImpl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 角色 服务实现类
 * </p>
 *
 * @author zenghualu
 * @since 2017-06-26
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<RoleMapper, Role> implements IRoleService {

	@Autowired
	IUserRoleService userRoleServ;
	@Autowired
	ISysuserService sysuserServ;
	@Autowired
	RoleMapper roleMapper;

	/**
	 *  根据用户id获取所有角色
	 */
	@Override
	public List<Role> getRolesByUserId(String userid) throws CommonException {

		// 根据用户id在用户角色表中获取相关记录
		List<UserRole> userRoles = userRoleServ.getRolesByUserId(userid);

		// 当没有获取到任何记录时，下面语句将不会执行
		if (null == sysuserServ.selectById(userid) || userRoles.size() <= 0) {

			return null;
		}

		// 将记录中的role_id获取到一个集合中
		List<String> ids = new ArrayList<>();
		for (UserRole userRole : userRoles) {
			ids.add(userRole.getRoleId());
		}

		// 通过批ID方法获取所有的角色
		List<Role> roles = this.selectBatchIds(ids);

		return roles;
	}

	public Role getInitRole() throws CommonException {/*-?|RoleServiceImpl|zenghualu|c1|?*/

		Role initRole = roleMapper.getRoleByName(Constant.TABLE_ROLE_NAME_DESAINER);

		if (initRole != null)
			return initRole;
		List<Role> roles = this.selectList(null);
		if (roles != null) {
			return roles.get(0);
		} else {
			throw new CommonException(CommonConstant.RESULT_CODE_NOT_FOUND,
					getMessage(MsgConstant.RET_ROLE_SELECT_NOTEXIST));
		}

	}

	// 通过用户名判断是否存在角色
	@Override
	public boolean isExist(String roleName) throws CommonException {/*-?|RoleServiceImpl|zenghualu|c2|?*/

//		Role role = roleMapper.getRoleByName(roleName);
		
		EntityWrapper<Role> ew=new EntityWrapper<>();
		ew.setEntity(new Role());
		ew.eq("role_name", roleName);
		
		Role role=this.selectOne(ew);
		
		if (role == null) {
			return false;
		}
		return true;
	}

}
